package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.R;
import com.ruan.common.Result;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.pojoExt.ParticipantExt;
import com.ruan.pojoExt.TaskExt;
import com.ruan.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.time.*;
import java.time.chrono.ChronoLocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/tasks")
public class TasksController {
    @Autowired
    private TasksService tasksService;
    @Autowired
    private OnDutyMapper onDutyMapper;
    @Autowired
    private TasksMapper tasksMapper;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private LineMapper lineMapper;
    @Autowired
    private WorkShopMapper workShopMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ProjectService peojectService;
    @Autowired
    private ProjectAssignmentsService projectAssignmentsService;
    @Autowired
    private ParticipantMapper participantMapper;
    @Autowired
    PositionService positionService;

    @GetMapping("/dismissedTask/{taskId}")
    public Result dismissedTask(@PathVariable String taskId){
        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Tasks::getId,taskId);

        Tasks task = tasksMapper.selectOne(queryWrapper);
        if (task == null) {
            return new Result(Code.DELETE_ERR,"任务不存在");
        }
        //今天的不能删除??
//        LocalDate taskDate = LocalDate.from(task.getDate());
        // 将 LocalDate 转换为 LocalDateTime
//        LocalDateTime taskDateTime = taskDate.atStartOfDay(); // 转换为当天的开始时间

//        LocalDateTime nowDateTime = LocalDateTime.now(); // 当前的日期和时间
//        LocalDate dateOnly = nowDateTime.toLocalDate();
//        LocalDateTime dateOnlyDateTime = dateOnly.atStartOfDay(); // 转换为 LocalDateTime，时间部分为 00:00:00
//        System.out.println("taskDateTime是："+taskDateTime);
//        System.out.println("nowDateTime是："+dateOnlyDateTime);
//        if (!taskDateTime.isBefore(dateOnlyDateTime)) {
//            return new Result(Code.DELETE_ERR,"当天的任务不能删除");
//        }
//        queryWrapper.notIn(Tasks::getDate,LocalDate.now());
        queryWrapper.eq(Tasks::getCompletionStatus,Tasks.CompletionStatus.completed);
        //List<Tasks> tasksList = tasksMapper.selectList(queryWrapper);
        tasksMapper.delete(queryWrapper);
        return new Result(Code.DELETE_OK,"任务删除成功");
    }

    @PostMapping("/page/{currentPage}/{pageSize}")
    public Result<Page> page(@PathVariable int currentPage,
                        @PathVariable int pageSize,
                        @RequestBody QueryTasksCondition queryTasksCondition){//第三个参数 name 可能是从前端的用户输入或者页面的搜索框中获取的
        //System.out.println("task的page传来的参数是："+currentPage+pageSize+queryTasksCondition);
        Page<Tasks> iPage=new Page<>(currentPage,pageSize);
        Page<TaskExt> iPageExt = new Page<>();
        //根据任务名模糊搜索
        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper();
        //TODO 根据时间搜索该时间段内的任务
        //首先是自己的任务(queryTasksCondition.getId()不传就是查的所有的任务)
        queryWrapper.eq(queryTasksCondition.getId()!=null &&
                !queryTasksCondition.getId().equals(""),
                Tasks::getEmployeeId, queryTasksCondition.getId());

        //根据时间范围搜索
        List<LocalDateTime> dateRange = queryTasksCondition.getDateRange();
//        System.out.println("dateRange是:"+dateRange);
        if (dateRange != null && dateRange.size() == 2) {
            LocalDate startDate = LocalDate.from(dateRange.get(0).plusDays(1).toLocalDate().atStartOfDay()); // 由于时区的影响，需要加一天
//            System.out.println("开始时间："+startDate);
            LocalDate endDate = LocalDate.from(dateRange.get(1).plusDays(1).toLocalDate().atStartOfDay());
//            System.out.println("结束时间："+endDate);
            // 进行日期转换和查询
            queryWrapper.between(Tasks::getDate, startDate, endDate);
        }

        //根据项目名模糊搜索(有可能为空)
        LambdaQueryWrapper<Project> projectWrapper =new LambdaQueryWrapper<>();
        projectWrapper.like(queryTasksCondition.getProjectName()!=null &&
                        !queryTasksCondition.getProjectName().equals(""),
                Project::getProjectName,queryTasksCondition.getProjectName());
        List<Project> projectList = projectMapper.selectList(projectWrapper);
        List<Long> projectIds = projectList.stream().map(Project::getId).collect(Collectors.toList());
        if(projectIds == null || projectIds.size() == 0){
            queryWrapper.in(Tasks::getProjectId, -1);
        }else {
            queryWrapper.in(queryTasksCondition.getProjectName()!=null &&
                    !queryTasksCondition.getProjectName().equals(""),
                    Tasks::getProjectId, projectIds);
        }

        //根据生产线名模糊搜索
        LambdaQueryWrapper<Line> lineWrapper =new LambdaQueryWrapper<>();
        lineWrapper.like(queryTasksCondition.getLineName()!=null &&
                        !queryTasksCondition.getLineName().equals(""),
                        Line::getLineName,queryTasksCondition.getLineName());
        List<Line> lineList = lineMapper.selectList(lineWrapper);
        List<Long> lineIds = lineList.stream().map(Line::getId).collect(Collectors.toList());
        if(lineIds == null || lineIds.size() == 0){
            queryWrapper.in(Tasks::getLineId, -1);
        }else {
            queryWrapper.in(Tasks::getLineId, lineIds);
        }
        //根据车间名模糊搜索
        LambdaQueryWrapper<WorkShop> workShopWrapper =new LambdaQueryWrapper<>();
        workShopWrapper.like(queryTasksCondition.getWorkshopName()!=null &&
                !queryTasksCondition.getWorkshopName().equals(""),
                WorkShop::getWorkShopName,queryTasksCondition.getWorkshopName());
        List<WorkShop> workShopList = workShopMapper.selectList(workShopWrapper);
        List<Long> workShopIds = workShopList.stream().map(WorkShop::getId).collect(Collectors.toList());
        if(workShopIds == null || workShopIds.size() == 0) {
            queryWrapper.in(Tasks::getWorkshopId, -1);
        } else {
            queryWrapper.in(Tasks::getWorkshopId, workShopIds);
        }
        //根据任务完成状态搜索(意味着最新的记录会排在最前面，旧的记录会排在后面)
        queryWrapper.like(!queryTasksCondition.getCompletionStatus().equals("") &&
                queryTasksCondition.getCompletionStatus()!=null,
                Tasks::getCompletionStatus,queryTasksCondition.getCompletionStatus());

        //根据时间排序
        queryWrapper.orderByDesc(Tasks::getDate);

        tasksService.page(iPage,queryWrapper);

        BeanUtils.copyProperties(iPage,iPageExt,"records");
        //处理
        List<Tasks> records = iPage.getRecords();
        List<TaskExt> list = records.stream().map((item) -> {
            TaskExt taskExt = new TaskExt();
            BeanUtils.copyProperties(item,taskExt);
            Long employeeId = item.getEmployeeId();
            Long projectId = item.getProjectId();
            Long lineId = item.getLineId();
            Long workshopId = item.getWorkshopId();
            //根据employeeId查任务负责人
            Employee employee = null;
            Project project = null;
            Line line = null;
            WorkShop workshop = null;
            if(employeeId != null){
                employee = employeeService.getById(employeeId);
            }
            if(employee != null){//能查到任务负责人
                String ename = employee.getName();
                taskExt.setEmployeeName(ename);
            }
            if(projectId != null){
                project = projectMapper.selectById(projectId);
            }
            if(project != null){//能查到任务相关项目
                String projectName = project.getProjectName();
                taskExt.setProjectName(projectName);
            }
            if(lineId != null){
                line = lineMapper.selectById(lineId);
            }
            if(line != null){//能查到任务生产线
                String lineName = line.getLineName();
                taskExt.setLineName(lineName);
            }
            if(workshopId != null){
                workshop = workShopMapper.selectById(workshopId);
            }
            if(workshop != null){//能查到任务车间
                String workshopName = workshop.getWorkShopName();
                taskExt.setWorkshopName(workshopName);
            }

            return taskExt;
        }).collect(Collectors.toList());
        iPageExt.setRecords(list);
        return new Result<>(Code.SELECT_OK,iPageExt);//(iPageExt);
    }

//params选项，通常用于 GET 请求，而不是 POST 请求。
//对于 POST 请求，可以将参数直接放在请求体中，而不是使用params。
    @GetMapping("/getDailyEmployeeTasks")
    public Result getDailyEmployeeTasks(@RequestParam String date){
        //System.out.println("getDailyEmployeeTasks传来的参数是："+date);
        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper<>();
        //今天
        queryWrapper.eq(Tasks::getDate,date);
        //必须是123456线的
        LambdaQueryWrapper<Line> lineWrapper = new LambdaQueryWrapper<>();
        lineWrapper.like(Line::getLineName,"线");
        List<Line> lineList = lineMapper.selectList(lineWrapper);
        List<Long> lineIds = lineList.stream().map(Line::getId).collect(Collectors.toList());
        queryWrapper.in(Tasks::getLineId,lineIds);
        List<Tasks> tasksList = tasksMapper.selectList(queryWrapper);
        //哪天(当天)，什么员工，在什么线，什么车间，为了什么项目而工作
        Map<String,List> map = new HashMap();
        List<TaskExt> taskExtList = new ArrayList();
        List<TaskExt> taskExtList2 = new ArrayList();
        List<TaskExt> taskExtList3 = new ArrayList();
        List<TaskExt> taskExtList4 = new ArrayList();
        List<TaskExt> taskExtList5 = new ArrayList();
        List<TaskExt> taskExtList6 = new ArrayList();
        for (Tasks tasks : tasksList) {
            TaskExt taskExt = new TaskExt();
            BeanUtils.copyProperties(tasks,taskExt);
            Long employeeId = tasks.getEmployeeId();
            Long projectId = tasks.getProjectId();
            Long lineId = tasks.getLineId();
            Long workshopId = tasks.getWorkshopId();
            Employee employee = employeeService.getById(employeeId);
            Project project = projectMapper.selectById(projectId);
            Line line = lineMapper.selectById(lineId);
            WorkShop workshop = workShopMapper.selectById(workshopId);
            if(employee != null){
                taskExt.setEmployeeName(employee.getName());
                taskExt.setAvatar(employee.getAvatar());
                taskExt.setJobId(employee.getJobId());
            }

            if(project != null){
                taskExt.setProjectName(project.getProjectName());
            }
            if(line != null){
                taskExt.setLineName(line.getLineName());
            }
            if(workshop != null){
                taskExt.setWorkshopName(workshop.getWorkShopName());
            }
            //存入一线
            if(tasks.getLineId() == 2){
                taskExtList.add(taskExt);
            }
            //存入二线
            if(tasks.getLineId() == 3){
                taskExtList2.add(taskExt);
            }
            //存入三线
            if(tasks.getLineId() == 4){
                taskExtList3.add(taskExt);
            }
            //存入四线
            if(tasks.getLineId() == 5){
                taskExtList4.add(taskExt);
            }
            //存入五线
            if(tasks.getLineId() == 6){
                taskExtList5.add(taskExt);
            }
            //存入六线
            if(tasks.getLineId() == 7){
                taskExtList6.add(taskExt);
            }
            map.put("1",taskExtList);
            map.put("2",taskExtList2);
            map.put("3",taskExtList3);
            map.put("4",taskExtList4);
            map.put("5",taskExtList5);
            map.put("6",taskExtList6);
        }
        //System.out.println("getDailyEmployeeTasks返回的结果是："+map);
        return new Result(Code.SELECT_OK,map);
    }

    /**
     * 打卡上班获取相关任务信息
     * @param employeeId
     * @return
     */
    @GetMapping("/getTasks")
    public Result getTasks(@RequestParam String employeeId){
        //获取该员工手上的参与的所有未过期的？？？项目
        LambdaQueryWrapper<Project> projectQueryWrapper = new LambdaQueryWrapper<>();
        //projectQueryWrapper.ge(Project::getEndDate, LocalDate.now());

        LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
        //在参与人表里找
        queryWrapper1.eq(Participant::getEmployeeId,employeeId);
        List<Participant> participantList = participantMapper.selectList(queryWrapper1);

        //获取该员工参与的所有项目的id
        List<Long> projectIds = null;
        if(participantList != null && participantList.size() > 0) {
            projectIds = participantList.stream().map(Participant::getProjectId).collect(Collectors.toList());
        }
        //projectIds里应该是自己是负责人的项目
        if (projectIds != null && projectIds.size() > 0) {
            LambdaQueryWrapper<Project> selfQueryWrapper = new LambdaQueryWrapper<>();
            selfQueryWrapper.eq(Project::getEmployeeId, employeeId);
            selfQueryWrapper.in(Project::getId, projectIds);
            List<Project> projectList = projectMapper.selectList(selfQueryWrapper);
            projectIds = projectList.stream().map(Project::getId).collect(Collectors.toList());
        }
        //projectIds应该排除掉已完成的项目，不能给已完成的项目的参与人员打卡
        LambdaQueryWrapper<Project> excludeIdsQueryWrapper = new LambdaQueryWrapper<>();
        if (projectIds != null && projectIds.size() > 0) {
            excludeIdsQueryWrapper.in(Project::getId, projectIds);
            excludeIdsQueryWrapper.ne(Project::getCompletionStatus, Project.CompletionStatus.completed)
                    .or().ge(Project::getEndDate, LocalDate.now());
            //而且需要项目未过期
//            excludeIdsQueryWrapper.ge(Project::getEndDate, LocalDate.now());
            List<Project> projectList = projectMapper.selectList(excludeIdsQueryWrapper);
            projectIds = projectList.stream().map(Project::getId).collect(Collectors.toList());
        }

        if (projectIds == null || projectIds.size() == 0) {
            projectQueryWrapper.eq(Project::getId, -1);
            // 不能不查，但是为了防止projectIds为空时查询报错，这里设置一个不存在的id
        } else {
            projectQueryWrapper.in(projectIds != null && projectIds.size() > 0,
                    Project::getId, projectIds);
            //已完成就不能代替打卡了
            projectQueryWrapper.ne(Project::getCompletionStatus, Project.CompletionStatus.completed);
            projectQueryWrapper.orderByDesc(Project::getEndDate);
        }
        LambdaQueryWrapper<Employee> employeeQueryWrapper = new LambdaQueryWrapper<>();
        //已离职的不用查
        employeeQueryWrapper.ne(Employee::getStatus,"离职");
        //排除掉自己
        employeeQueryWrapper.ne(Employee::getId,employeeId);
        //只能帮自己当前负责项目的参与人员打卡
        List<Long> employeeIds2 = null;
//        System.out.println("projectIds.size()是："+projectIds.size());
        if(projectIds != null && projectIds.size() > 0) {
//            System.out.println("projectIds是："+projectIds);
            LambdaQueryWrapper<Participant> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.in(Participant::getProjectId, projectIds);
            List<Participant> participantList2 = participantMapper.selectList(queryWrapper2);
            employeeIds2 = participantList2.stream().map(Participant::getEmployeeId).collect(Collectors.toList());
        }
        if(employeeIds2 == null || employeeIds2.size() == 0){
            employeeQueryWrapper.eq(Employee::getId,-1);
        }else {
            employeeQueryWrapper.in(employeeIds2 != null &&
                            employeeIds2.size() > 0,
                    Employee::getId,employeeIds2);
        }
        employeeQueryWrapper.orderByAsc(Employee::getJobId);
        List<Project> projectList = projectMapper.selectList(projectQueryWrapper);

        List<Employee> employeeList = employeeMapper.selectList(employeeQueryWrapper);
//        System.out.println("employeeList是"+employeeList);

        // 假设根据 Employee 的某个属性进行去重，例如 ID
//        List<Employee> distinctEmployees = employeeList.stream()
//                .distinct() // 如果 Employee 类重写了 equals 和 hashCode 方法，这样直接去重
//                .collect(Collectors.toList());

//        如果你需要根据某个特定属性去重，比如 id，你可以使用 Collectors.toMap() 来帮助处理：
//        java
//        Map<Integer, Employee> employeeMap = employeeList.stream()
//                .collect(Collectors.toMap(Employee::getId, employee -> employee, (existing, replacement) -> existing));
//        List<Employee> distinctEmployeesById = new ArrayList<>(employeeMap.values());

//        LambdaQueryWrapper<Line> queryWrapper = new LambdaQueryWrapper<>();
        //获取 所有的记录，则不需要在 queryWrapper 中设置任何条件，可以直接调用 selectList 方法

        List<Line> lineList = lineMapper.selectList(null);
        List<WorkShop> workShopList = workShopMapper.selectList(null);
        Map<String, Object> map = new HashMap();
        //可能该员工手上没有项目
        if(projectList != null){
            map.put("projectList",projectList);
        }
        map.put("employeeList",employeeList);
        map.put("lineList",lineList);
        map.put("workShopList",workShopList);
        return new Result(Code.SELECT_OK,map);
    }

    /**
     * 打卡下班获取参与员工的列表
     * @param employeeId
     * @return
     */
    @GetMapping("/getEmployees")
    public Result getEmployees(@RequestParam String employeeId){
        //首先自己需要先打卡上班
        LambdaQueryWrapper<OnDuty> selfondutyQueryWrapper = new LambdaQueryWrapper<>();
        selfondutyQueryWrapper.eq(OnDuty::getEmployeeId,employeeId);
        Date day = new Date(System.currentTimeMillis());
        selfondutyQueryWrapper.eq(OnDuty::getDay,day);
        if(onDutyMapper.selectCount(selfondutyQueryWrapper) == 0){
            return new Result(Code.ONDUTY_ERR,"请先打卡上班！");
        }
        LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
        //在参与人表里找
        queryWrapper1.eq(Participant::getEmployeeId,employeeId);

        List<Participant> participantList = participantMapper.selectList(queryWrapper1);
        //获取该员工参与的所有项目的id
        List<Long> projectIds = null;
        if(participantList != null && participantList.size() > 0){
            projectIds = participantList.stream().map(Participant::getProjectId).collect(Collectors.toList());
        }
        //projectIds里应该是自己是负责人的项目
        if (projectIds != null && projectIds.size() > 0) {
            LambdaQueryWrapper<Project> selfQueryWrapper = new LambdaQueryWrapper<>();
            selfQueryWrapper.eq(Project::getEmployeeId, employeeId);
            selfQueryWrapper.in(Project::getId, projectIds);
            List<Project> projectList = projectMapper.selectList(selfQueryWrapper);
            projectIds = projectList.stream().map(Project::getId).collect(Collectors.toList());
        }
        //projectIds应该排除掉已完成的项目，不能给已完成的项目的参与人员打卡
        LambdaQueryWrapper<Project> excludeIdsQueryWrapper = new LambdaQueryWrapper<>();
        if (projectIds != null && projectIds.size() > 0) {
            excludeIdsQueryWrapper.in(Project::getId, projectIds);
            excludeIdsQueryWrapper.ne(Project::getCompletionStatus, Project.CompletionStatus.completed)
                     .or().ge(Project::getEndDate, LocalDate.now());
            List<Project> projectList = projectMapper.selectList(excludeIdsQueryWrapper);
            projectIds = projectList.stream().map(Project::getId).collect(Collectors.toList());
        }

        LambdaQueryWrapper<Employee> employeeQueryWrapper = new LambdaQueryWrapper<>();
        //已离职的不用查
        employeeQueryWrapper.ne(Employee::getStatus,"离职");
        //排除掉自己
        employeeQueryWrapper.ne(Employee::getId,employeeId);

        //只能帮自己当前负责项目的参与人员打卡
        List<Long> employeeIds = null;
        if(projectIds != null && projectIds.size() > 0) {
            LambdaQueryWrapper<Participant> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.in(Participant::getProjectId, projectIds);
            List<Participant> participantList2 = participantMapper.selectList(queryWrapper2);
            if (participantList2 != null && participantList2.size() > 0) {
                employeeIds = participantList2.stream().map(Participant::getEmployeeId).collect(Collectors.toList());
            }
        }
        if(employeeIds == null || projectIds.size() == 0){
            employeeQueryWrapper.eq(Employee::getId,-1);
        }else {
            employeeQueryWrapper.in(employeeIds != null && employeeIds.size() > 0,
                    Employee::getId,employeeIds);
        }

        //必须是当天已打卡上班，但是未打卡下班的
        LambdaQueryWrapper<OnDuty> onDutyQueryWrapper = new LambdaQueryWrapper<>();
        List<OnDuty> onDutyList = null;
        if (employeeIds != null && employeeIds.size()>0) {
            onDutyQueryWrapper.in(OnDuty::getEmployeeId, employeeIds);
            onDutyQueryWrapper.eq(OnDuty::getDay,day);
            onDutyQueryWrapper.isNotNull(OnDuty::getArriveTime);
            onDutyQueryWrapper.isNull(OnDuty::getLeaveTime);
            onDutyList = onDutyMapper.selectList(onDutyQueryWrapper);
        }else {
            return new Result(Code.SELECT_ERR,"没有所负责项目的参与人员的上班打卡数据");
        }
//        Date day = new Date(System.currentTimeMillis());

        List<Long> employeeIds1 = null;
        if(onDutyList != null && onDutyList.size() >0) {
            employeeIds1 = onDutyList.stream().map(OnDuty::getEmployeeId).collect(Collectors.toList());
        }

        if(employeeIds1 == null || employeeIds1.size() == 0){
            employeeQueryWrapper.eq(Employee::getId,-1);
        }else {
            employeeQueryWrapper.in(employeeIds1 != null && employeeIds1.size() > 0,
                    Employee::getId,employeeIds1);
        }

        List<Employee> employeeList = employeeMapper.selectList(employeeQueryWrapper);
//        System.out.println("employeeList是"+employeeList+employeeList.size());
        if(employeeList!=null && employeeList.size() > 0){
            return new Result(Code.SELECT_OK,employeeList);
        }
        return new Result(Code.SELECT_ERR,"无数据");
    }

    @GetMapping("/getParticipantList")
    public Result getParticipantList(@RequestParam String projectId){
//        System.out.println("getParticipantList的参数是"+projectId);
        LambdaQueryWrapper<Participant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Participant::getProjectId,projectId);
        List<Participant> participantList = participantMapper.selectList(queryWrapper);
//        System.out.println("该负责人负责的项目的participantList参与人员id有："+participantList);
        if(participantList!=null){
            List<ParticipantExt> participantExtList = new ArrayList<>();
            for(Participant participant : participantList){
                ParticipantExt participantExt = new ParticipantExt();
                Project project = peojectService.getById(participant.getProjectId());

                //已离职..的选不中
                LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Employee::getId,participant.getEmployeeId());
                queryWrapper1.notIn(Employee::getStatus,"离职","待审核");
                Employee employee = employeeMapper.selectOne(queryWrapper1);
//                Employee employee = employeeService.getById(participant.getEmployeeId());

                participantExt.setProjectName(project.getProjectName());
                if (employee != null) {
                    if(employee.getPositionId() != null){
                        Position position = positionService.getById(employee.getPositionId());
                        participantExt.setPositionName(position.getPname());
                    }
                    if (employee.getName() != null) {
                        participantExt.setEmployeeName(employee.getName());
                    }
                    if (employee.getJobId() != null) {
                        participantExt.setJobId(employee.getJobId());
                    }
//                    System.out.println("工号："+participantExt.getJobId());
                    //确定没有离职之后再进行基础属性搬迁
                    BeanUtils.copyProperties(participant,participantExt);
                    participantExtList.add(participantExt);
                }

            }
            return new Result(Code.SELECT_OK,participantExtList,"项目参与人员查询成功");
        }
        return new Result(Code.SELECT_ERR,"项目参与人员查询失败");
    }

    /**
     * 员工任务完成确认
     */
    @GetMapping("/approvalTask/{id}")
    public Result approvalTask(@PathVariable Integer id){
//        System.out.println("approvalTask传来的任务id是"+id);
        if (tasksService.approvalTask(id)){
            return new Result(Code.UPDATE_OK,"任务确认完成！");
        }
        return new Result(Code.UPDATE_ERR,"任务确认失败！");
    }

//    @GetMapping("/checkTodayTasks")
//    public Result checkTodayTasks(@RequestParam String employeeId) {
//        List<TaskExt> taskExtList = tasksService.getTodayTasks(employeeId);
//        if(taskExtList.size() > 0){//isEmpty() ???
//            return new Result(Code.SELECT_ERR,"今日任务查找失败");
//        }
//        return new Result(Code.SELECT_OK,taskExtList,"今日任务查找成功");
//    }

    /**
     * 员工每日任务
     */
    @PostMapping("/dailyTask/{currentPage}/{pageSize}")
    public R<Page> getDailyTask(@PathVariable int currentPage,
                        @PathVariable int pageSize,
                        @RequestBody QueryEmployeeCondition queryEmployeeCondition){
        //System.out.println("dailyTask传来的参数是：" +currentPage+pageSize+queryEmployeeCondition);
        Page<Tasks> iPage=new Page<>(currentPage,pageSize);
        Page<TaskExt> iPageExt = new Page<>();

        LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper();
        //根据任务完成状态搜索
        queryWrapper.like(queryEmployeeCondition.getStatus()!=null &&
                        !queryEmployeeCondition.getStatus().equals(""),
                Tasks::getCompletionStatus,queryEmployeeCondition.getStatus());
        //固定查询各位组长分配给自己的任务
        //前端传来个人的id
        queryWrapper.eq(Tasks::getEmployeeId,queryEmployeeCondition.getId());
        queryWrapper.orderByDesc(Tasks::getDate);
        tasksService.page(iPage,queryWrapper);
        BeanUtils.copyProperties(iPage,iPageExt,"records");
        //忽略掉records(存储了当前页上要显示的对象记录。代表了在 iPage 中的具体数据集（即表中查到的记录的列表)
        List<Tasks> records = iPage.getRecords();
        //item:遍历出来的每一个对象
        List<TaskExt> list = records.stream().map((item) -> {
            TaskExt taskExt = new TaskExt();//只有TaskExt符合页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,taskExt);//填充入task的普通属性

//获取搜索第三个属性所要用到的id => ename
            Long employeeId = item.getEmployeeId();//拿到了每个任务所对应的分配表里的项目小组长的id
            //根据employeeId查任务负责人
            Employee employee = new Employee();
            if(employeeId != null){
               employee = employeeService.getById(employeeId);
            }
            if(employee != null){//能查到任务负责人
                String ename = employee.getName();
                taskExt.setEmployeeName(ename);
            }
            return taskExt;
            //就转成集合了，赋给List<TaskExt> list
        }).collect(Collectors.toList());
        //System.out.println("list有了什么"+list);
        //list获得了改造过后的taskExt集合之后，被用来设置page对象的Records属性
        iPageExt.setRecords(list);

        return R.success(iPageExt);
    }

    @PutMapping("/updateTask")
    public Result update(@RequestBody Tasks tasks){
//‘@RequestBody’注释表明‘Tasks’对象将从请求体中反序列化，通常采用JSON或XML格式。
        log.info("修改任务信息：："+tasks.toString());

        long id = Thread.currentThread().getId();
        //log.info("当前线程id为：{}",id);
        boolean a = tasksService.updateById(tasks);//updateById继承自父接口IService(由mybatis-plus提供)
        if(a){
            return new Result(Code.UPDATE_OK,"任务信息修改成功");
        }
        return new Result(Code.UPDATE_ERR,"任务修改失败");
    }
    //新增任务
    @PostMapping("/addTask")
    @Transactional
    public Result save(@RequestBody TaskQuery taskQuery){
//        log.info("新增任务，任务信息：{}",taskQuery.toString());

        if(taskQuery.getLineId() == null){
            return new Result(Code.SAVE_ERR,"请选择工作地点");
        }
        if(taskQuery.getWorkshopId() == null){
            return new Result(Code.SAVE_ERR,"请选择工作内容");
        }
        if(taskQuery.getEmployeeIds() == null || taskQuery.getEmployeeIds().size() == 0){
            return new Result(Code.SAVE_ERR,"请选择参与员工");
        }

        if(taskQuery.getEmployeeIds().size() != 0){
            Date day = new Date(System.currentTimeMillis());
            int punchIned = 0;
            for(String employeeId : taskQuery.getEmployeeIds()){
                Employee employee = employeeMapper.selectById(employeeId);
                if(employee == null || employee.getStatus().equals("离职")){
                    //显式设置事务回滚，否则会直接提交for循环里的一半的tasksService.save()
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return new Result(Code.SAVE_ERR,"有员工不存在或已离职");
                }
                LambdaQueryWrapper<Tasks> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Tasks::getEmployeeId,employeeId);
                queryWrapper.eq(Tasks::getDate,day);
                queryWrapper.eq(Tasks::getCompletionStatus,Tasks.CompletionStatus.incomplete);
                queryWrapper.eq(Tasks::getLineId,taskQuery.getLineId());
                int count = tasksMapper.selectCount(queryWrapper);
//                System.out.println("count是"+count);
                //当天该地点的任务完成之前都不能添加
                if(count > 0){
                    punchIned = punchIned + 1;
//                    System.out.println("punchIned是"+punchIned);
                    //删除多余的任务记录，只留下一条
                    List<Tasks> list = tasksMapper.selectList(queryWrapper);
                    // 保留 list 中的第一条记录，其他的删除
                    // 确保保留的记录是否正确
                    if(list.size() > 1){
                        Tasks recordToKeep = list.get(0);
                        // 删除多余的记录
                        for (Tasks task : list) {
                            if (!task.equals(recordToKeep)) {
                                tasksMapper.deleteById(task.getId());
                            }
                        }
                    }
//                    return new Result(Code.SAVE_ERR,"该员工今日已有该线的任务");
                }else{
                    Tasks task = new Tasks();
                    //可能该任务不与任何项目相关
                    if(taskQuery.getProjectId() != null){
                        if(projectService.getById(taskQuery.getProjectId()) == null){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return new Result(Code.SAVE_ERR,"该项目不存在，请重新选择");
                        }
                        task.setProjectId(taskQuery.getProjectId());
                    }
                    task.setLineId(taskQuery.getLineId());
                    task.setWorkshopId(taskQuery.getWorkshopId());
                    task.setEmployeeId(Long.valueOf(employeeId));
                    task.setCompletionStatus(Tasks.CompletionStatus.incomplete);
                    //开始时间
                    task.setDate(LocalDateTime.now());
                    tasksService.save(task);
                }
            }
            if(punchIned > 0){
//                System.out.println("punchIned0是"+punchIned);
                return new Result(Code.SAVE_ERR,punchIned,"有"+punchIned+"个员工今日该地点的任务还未完成");
            }
            return new Result(Code.SAVE_OK,"共添加了"+Integer.parseInt(String.valueOf(taskQuery.getEmployeeIds().size() -
                    punchIned))+"个任务");
        }
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        return new Result(Code.SAVE_ERR,"任务添加失败，请选择参与员工");
    }
}
